package com.neusoft.techan.controller;

import org.springframework.web.bind.annotation.*;

import com.neusoft.techan.model.Goods;
import com.neusoft.techan.model.Orderdetail;
import com.neusoft.techan.model.Orders;
import com.neusoft.techan.model.User;
import com.neusoft.techan.service.GoodsService;
import com.neusoft.techan.service.OrderdetailService;
import com.neusoft.techan.service.OrdersService;
import com.neusoft.techan.service.UserService;
import com.neusoft.techan.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 订单Controller
 * 
 * @author ThinkPad
 *
 */
@Controller
@RequestMapping("/orders")
public class OrdersController {
	@Autowired
	private OrdersService ordersService;
	@Autowired
	private OrderdetailService orderdetailService;
	@Autowired
	private UserService userService;
	@Autowired
	private GoodsService goodsService;

	/**
	 * 新增订单
	 */
	@ResponseBody
	@RequestMapping(value = "/insert", method = RequestMethod.POST)
	@Transactional
	public Result<String> insert(@RequestBody Orders orders) {
		BigDecimal orderTotalPrice = new BigDecimal(0);

		// 计算总金额
		for (Orderdetail detail : orders.getOrderdetails()) {
			BigDecimal totalprice = detail.getTotalprice();
			orderTotalPrice = orderTotalPrice.add(totalprice);
		}

		// 查询账户余额，和订单总金额比较
		User user = userService.selectByPrimaryKey(orders.getBuyerid());
		if (user.getMoney().compareTo(orderTotalPrice) != 1) {
			return ResultGenerator.genFailResult("余额不足，扣款失败！");
		}

		// 新增订单
		orders.setCreateTime(new Date());
		orders.setTotalPrice(orderTotalPrice);
		ordersService.insert(orders);

		// 新增订单明细
		for (Orderdetail detail : orders.getOrderdetails()) {
			detail.setOrderid(orders.getId());
			orderdetailService.insert(detail);

			// 增加销量和减少库存
			Goods record = goodsService.selectByPrimaryKey(detail.getGoodsid());
			record.setSellNum(record.getSellNum() + detail.getGoodsnum());
			record.setInventory(record.getInventory() - detail.getGoodsnum());
			goodsService.updateByPrimaryKey(record);
		}

		// 扣款
		user.setMoney(user.getMoney().subtract(orderTotalPrice));
		userService.updateByPrimaryKey(user);

		return ResultGenerator.genSuccessResult();
	}

	/**
	 * 删除
	 */
	@ResponseBody
	@RequestMapping(value = "/delete/{ids}", method = RequestMethod.GET)
	public Result<String> delete(@PathVariable("ids") String ids) {
		if (null == ids || ids.equals("")) {
			return ResultGenerator.genFailResult(null);
		}
		String str[] = ids.split(",");
		for (String s : str) {
			ordersService.deleteByPrimaryKey(Integer.valueOf(s));
		}
		return ResultGenerator.genSuccessResult();
	}

	/**
	 * 更新
	 */
	@ResponseBody
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public Result<String> update(@RequestBody Orders orders) {
		int res = ordersService.updateByPrimaryKey(orders);
		if (res == 1) {
			return ResultGenerator.genSuccessResult();
		} else {
			return ResultGenerator.genFailResult(null);
		}
	}

	/**
	 * 主键查询
	 */
	@ResponseBody
	@RequestMapping(value = "/info/{id}", method = RequestMethod.GET)
	public Result<?> selectById(@PathVariable("id") int id) {
		Orders orders = ordersService.selectByPrimaryKey(id);
		if (null == orders) {
			return ResultGenerator.genFailResult(null);
		} else {
			return ResultGenerator.genSuccessResult(orders);
		}
	}

	/**
	 * 条件和排序的分页查询
	 */
	@ResponseBody
	@RequestMapping(value = "/search", method = RequestMethod.POST)
	public HashMap<String, Object> search(@RequestParam(value = "page", required = false) String page,
			@RequestParam(value = "rows", required = false) String rows, Orders orders, HttpServletResponse response) {
		// 设置分页参数
		Map<String, Object> map = new HashMap<String, Object>();
		if (page != null && rows != null) {
			PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
			map.put("start", pageBean.getStart());
			map.put("size", pageBean.getPageSize());
		}

		// 设置排序参数
		map.put("sort", "id");

		// 发送数据
		List<Orders> list = ordersService.select(map);
		int total = ordersService.count(map);
		HashMap<String, Object> result = new HashMap<>();
		result.put("rows", list);
		result.put("total", total);
		return result;
	}

	/**
	 * 根据buyerid查询订单
	 */
	@ResponseBody
	@RequestMapping(value = "/selectByBuyerid/{buyerid}", method = RequestMethod.GET)
	public Result<?> selectByUserid(@PathVariable("buyerid") int buyerid) {
		List<Orders> orders = ordersService.selectByUserid(buyerid);
		return ResultGenerator.genSuccessResult(orders);
	}

	/**
	 * 根据buyerid分页查询订单
	 */
	@ResponseBody
	@RequestMapping(value = "/selectPageByBuyerid", method = RequestMethod.POST)
	public Map<String,Object> selectPageByBuyerid(@RequestParam("userid") int userid, @RequestParam("page") String page,
			@RequestParam("rows") String rows) {
		int totalSize = ordersService.countByBuyerid(userid);
		int totalPage = totalSize % Integer.parseInt(rows) == 0 ? totalSize / Integer.parseInt(rows)
				: totalSize / Integer.parseInt(rows) + 1;
		// 设置分页参数
		Map<String, Object> map = new HashMap<String, Object>();
		if (page != null && rows != null) {
			PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
			map.put("start", pageBean.getStart());
			map.put("size", pageBean.getPageSize());
		}
		map.put("userid", userid);

		List<Orders> orders = ordersService.selectPageByUserid(map);
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("data", orders);
		resultMap.put("totalSize", totalSize);
		resultMap.put("totalPage", totalPage);
		resultMap.put("currPage", Integer.parseInt(page));

		return resultMap;
	}
}